package com.ly.mpayment.rest.up.hongshi;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.core.util.HttpClient;
import com.ly.mpayment.core.util.StringUtils;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("hongshi")
public class HongShiRest {

    Logger logger = Logger.getLogger(HongShiRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @SuppressWarnings("static-access")
    @Path("callBack")
    @POST
    public String callBack(String data) {
        logger.info("hongshi_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            JSONObject jsonD = JSONObject.parseObject(data);
            UpOrder order = upOrderService.findById(jsonD.getString("compayOrderNo"));
            if (order != null && jsonD.getString("status").equals("1") && order.getStatus() == Config.status[0]) {
                order.setRemark(jsonD.containsKey("card_id") ? jsonD.getString("card_id") : "" );
                RechargeRest.successUpOrder.add(order);
                jsonD.clear();
                jsonD.put("code","200");
                jsonD.put("msg","SUCCESS");
                return jsonD.toString();
            } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("status").equals("3")) {
                order.setRemark("");
                RechargeRest.failtUpOrder.add(order);
                jsonD.clear();
                jsonD.put("code","200");
                jsonD.put("msg","SUCCESS");
                return jsonD.toString();
            } else {
                logger.info("hongshi_not_found_order:" + jsonD.getString("compayOrderNo") + "," );
            }
        }
        return "0";
    }


    /**
     * 订单提交
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = new JSONObject();
        data.put("cid", shop.getAppId());
        data.put("card_code", order.getUpShopPro().getProductCode());
        data.put("charge_account",order.getUpphonenum());
        data.put("price", order.getRechargeamount().intValue()+".0");
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        // 运营商编码 【2:电信、3:移动、4联通】
        data.put("operator_code", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "3" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "4" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "2" : "1");
        data.put("compayOrderNo", order.getUporderuuid());
        //Md5签名，MD5(key+cid+card_code+charge_account+price+compayOrderNo+key)
        data.put("sign", MD5.md5(shop.getUpkey()+shop.getAppId()+order.getUpShopPro().getProductCode()+
                order.getUpphonenum()+data.getString("price") +order.getUporderuuid()+shop.getUpkey()).toUpperCase());
        String result = HttpClient.post(shop.getOrderCommitAddress(), data.toString());
        logger.info("commitOrder_hongshi:"+result+","+data.toString());
        if (!StringUtils.isBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("code") && json.getString("code").equals("200")) {
                this.upOrderService.updateUpOrderMsg(order,json.getString("order_card"),json.getString("result_message"));
            } else if(json.containsKey("code") && errorCode.contains(json.getString("code"))) {
                order.setRemark(json.getString("result_message"));
                RechargeRest.failtUpOrder.add(order);
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","提单失败");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }


    /**
     * 202	充值失败
     * 203	号码段不存在
     * 306	未找到运营商
     * 307	没有配置该货架
     * 420	商品价格异常请联系管理员
     * 401	此商品的获取为卡密类接口
     * 400	此商品暂未上线
     * 404	商户code不存在
     * 306	未找到运营商
     * 100	商户编号不存在
     * 106	渠道关闭
     * 610	余额不足
     * 600	Ip绑定
     * 620	订单号重复
     * 650	签名失败
     * -1	请求参数错误
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("202");
        add("203");
        add("306");
        add("307");
        add("420");
        add("401");
        add("400");
        add("404");
        add("100");
        add("106");
        add("610");
        add("600");
        add("620");
        add("650");
        add("-1");
    }};

    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("cid", shopInfo.getAppId());
        data.put("compayOrderNo", upOrder.getUporderuuid());
        data.put("sign", MD5.md5(shopInfo.getUpkey()+shopInfo.getAppId()+upOrder.getUporderuuid()+shopInfo.getUpkey()).toUpperCase());
        String result =  HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
        logger.info("hongshiqueryOrder:"+upOrder.getUpphonenum()+":"+result);
        if (!StringUtils.isBlank(result)) {
            JSONObject jsonD = JSONObject.parseObject(result);
            if( jsonD.getString("code").equals("200")){
                UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
                if (order != null && jsonD.getString("status").equals("1") && order.getStatus() == Config.status[0]) {
                    order.setRemark(jsonD.containsKey("card_id") ? jsonD.getString("card_id") :  jsonD.getString("result_message"));
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("status").equals("3")) {
                    order.setRemark(jsonD.getString("result_message"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    logger.info("hongshi_not_found_order:" + jsonD.toString() + ",");
                }
            }else if(jsonD.getString("code").equals("105")){
                upOrder.setRemark(jsonD.getString("result_message"));
                RechargeRest.failtUpOrder.add(upOrder);
            }
        }
    }

}
